package com.sunlee.common.core.redis.serializer;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.IOUtils;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Redis 序列化
 *
 * @author sunlee
 */
public class JsonRedisSerializer<T> implements RedisSerializer<T> {

    private static final ParserConfig DEFAULT_REDIS_CONFIG = new ParserConfig();

//    static {
//        DEFAULT_REDIS_CONFIG.setAutoTypeSupport(true);
//    }

    private final Class<T> type;

    public JsonRedisSerializer(Class<T> type) {
        this.type = type;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(IOUtils.UTF8);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        // 不序列化空值属性
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, IOUtils.UTF8);

        return JSON.parseObject(str, type, DEFAULT_REDIS_CONFIG);
    }
}